<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 2017/8/1
 * Time: 下午6:47
 */

namespace app\models;


use app\librarys\ccp\CCPRestSDK;
use Yii;

class Sms
{
    const CacheKey_SmsVerificationCode = 'sms_verification_code:';

    /**
     * 生成短信验证码
     * @param $phone
     * @param $timeValidity
     * @return int|string
     */
    public static function genSmsVerificationCode($phone, $timeValidity)
    {
        $verificationCode = rand(0, 999999);
        $verificationCode = str_pad($verificationCode, 6, '0', STR_PAD_LEFT);
        $cacheKey = self::CacheKey_SmsVerificationCode . $phone;
        \Yii::$app->cache->set($cacheKey, $verificationCode, $timeValidity * 60);

        return $verificationCode;
    }

    /**
     * 验证短信验证码
     * @param $phone
     * @param $verificationCode
     * @return bool
     */
    public static function authSmsVerificationCode($phone, $verificationCode)
    {
        // TODO 调试使用
        if ($verificationCode == '123456') {
            return true;
        }

        if (empty($verificationCode)) {
            User::log('phone'.$phone.'验证码为空.','Sms.php');
            return false;
        }
        $cacheKey = self::CacheKey_SmsVerificationCode . $phone;
        $cacheVerificationCode = \Yii::$app->cache->get($cacheKey);
        if ($verificationCode == $cacheVerificationCode) {
            \Yii::$app->cache->delete($cacheKey);
            return true;
        } else {
            User::log('phone'.$phone.'验证码错误：正确验证码：'.$cacheVerificationCode.'传入验证码:'.$verificationCode,'Sms.php');

            return false;
        }
    }

    /**
     * 发送短信验证码
     * @param $phone
     * @param $verificationCode
     */
    public static function sendSmsVerificationCode($phone, $verificationCode)
    {
        $t = Yii::$app->params['sms.TimeValidity'];
        Sms::sendSms($phone, [$verificationCode, $t], 201187);
    }

    public static function sendSms($to, $data, $template_id)
    {
        $result = ['id' => '', 'status' => '', 'message' => '', 'create_datetime' => ''];
        try {
            //发送短信
            // 初始化REST SDK

            $accountSid = Yii::$app->params['accountSid'];
            $accountToken = Yii::$app->params['accountToken'];
            $appId = Yii::$app->params['AppId'];
            $serverIP = Yii::$app->params['address'];
            $serverPort = Yii::$app->params['address_port'];
            $softVersion = Yii::$app->params['softVersion'];


            $rest = new CCPRestSDK($serverIP, $serverPort, $softVersion);
            $rest->setAccount($accountSid, $accountToken);
            $rest->setAppId($appId);

            // 发送模板短信

            $ccp_result = $rest->sendTemplateSMS($to, $data, $template_id);
            if ($ccp_result == NULL) {
//                $result['status'] = '1000';
//                $result['message'] = '系统错误(ccp)!';
//                static::returnAjax($result);
            }
            if ($ccp_result->statusCode != 0) {
                // 添加错误处理逻辑
//                $create_datetime = SmsDao::getDateTimeStr();
//                $result['status'] = (String)$ccp_result->statusCode;
//                $result['message'] = (String)$ccp_result->statusMsg;
//                SmsDao::add_t_sms_send_record($app_id, '', $to, $context, $result['status'], $create_datetime);
//                static::returnAjax($result);
            } else {
                //发送成功
//                $create_datetime = SmsDao::getDateTimeStr();
//                SmsDao::add_t_sms_send_record($app_id, '', $to, $context, 0, $create_datetime);
//                $id = Yii::$app->db->getLastInsertID();
//                $result['status'] = '0';
//                $result['id'] = $id;
//                $result['message'] = $context;
//                $result['create_datetime'] = $create_datetime;
//
//
//                static::returnAjax($result);
                /* $smsmessage = $ccp_result->TemplateSMS;
                 echo "dateCreated:".$smsmessage->dateCreated."<br/>";
                 echo "sysdate:"."<br/>";
                 echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";*/

            }
        } catch (\Exception $e) {
            $result['status'] = '1000';
            $result['message'] = '系统错误(sys)!' . $e->getMessage();
            Yii::error('发送短信错误:' . $e->getMessage());
//            static::returnAjax($result);
        }
    }
}